package com.planet.common.autoconfigure.email;

import com.planet.common.autoconfigure.PlanetSenderAbstract;
import com.planet.common.autoconfigure.utils.CodeGenerateUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.annotation.Resource;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2023/8/25
 * @Company EMAIL
 **/
@Slf4j
public class PlanetEmailSender extends PlanetSenderAbstract {

    @Resource
    JavaMailSenderImpl javaMailSender;

    @Value("${spring.mail.username:mis_wu1998@163.com}")
    private String from;

    private PlanetEmailProperties planetEmailProperties;

    public void setPlanetEmailProperties(PlanetEmailProperties planetEmailProperties){
        this.planetEmailProperties = planetEmailProperties;
    }


    @Override
    public Boolean emailSend(String[] recipients) {
        log.info("use planet emailSend ...");
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(recipients);
        String code = this.assertMessage(simpleMailMessage);
        try {
            javaMailSender.send(simpleMailMessage);
            //todo:缓存（幂等校验，60s后才可再次发送）
            return true;
        } catch (MailException e) {
            log.error("emailSend error==>{}",e.getMessage(),e);
        }
        return false;
    }

    private String assertMessage(@NonNull SimpleMailMessage simpleMailMessage){

        simpleMailMessage.setFrom(StringUtils.isBlank(planetEmailProperties.getSender())?from:planetEmailProperties.getSender());
        //assert simpleMailMessage.getFrom() == null || Objects.equals(simpleMailMessage.getFrom(), "") : "发件人信息不能为空";

        assert simpleMailMessage.getTo() == null || simpleMailMessage.getTo().length == 0: "收件人信息不能为空";

        if (StringUtils.isBlank(simpleMailMessage.getSubject())){
            simpleMailMessage.setSubject("登录验证码");
        }
        String smsCode = CodeGenerateUtil.get6BitCode();

        simpleMailMessage.setText("您本次登录的验证码为:"+smsCode+",切记保密,否则后果自负！！！");

        return smsCode;
    }
}
